package com.czn.shopdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czn.shopdemo.mapper.CartMapper;
import com.czn.shopdemo.mapper.GoodsMapper;
import com.czn.shopdemo.mapper.OrderItemMapper;
import com.czn.shopdemo.mapper.OrderMapper;
import com.czn.shopdemo.model.Cart;
import com.czn.shopdemo.model.Goods;
import com.czn.shopdemo.model.Order;
import com.czn.shopdemo.model.OrderItem;
import com.czn.shopdemo.model.enums.PayStatusEnum;
import com.czn.shopdemo.model.exception.CustomException;
import com.czn.shopdemo.service.OrderService;
import com.czn.shopdemo.utils.TokenInfoUtil;
import com.czn.shopdemo.utils.Utils;
import org.apache.tomcat.jni.Error;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.beans.ExceptionListener;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Zenan Chen
 * @date 2023/4/6 9:00
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CartMapper cartMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Order order, HttpServletRequest request) {
        // 插入订单数据
        order.setUpdateTime(new Date());
        order.setCreateTime(new Date());
        order.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
        order.setUserId(String.valueOf(TokenInfoUtil.getUserId(request)));
        // 设置订单为未支付状态
        order.setOrderStatus(PayStatusEnum.UnPaid.getPayStatusCode());
        orderMapper.insert(order);
        // 插入订单明细
        List<OrderItem> orderItemList = order.getOrderItemList();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            orderItem.setUpdateTime(new Date());
            orderItem.setCreateTime(new Date());
            orderItem.setOrderId(order.getUuid());
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", orderItem.getGoodsId());
            Goods goods = goodsMapper.selectOne(queryWrapper);
            // 校验下单商品是否超过库存
            if (orderItem.getCount() > goods.getNum()) {
                throw new CustomException("下单商品数量超过库存数量！", 211);
            }
            // 下单商品数量*商品的单价，得到下单的总价
            Double price = orderItem.getCount() * goods.getPrice();
            orderItem.setPrice(price);
            orderItemMapper.insert(orderItem);
            // 如果是通过购物车下单，则清除购物车的相关记录
            if (!Utils.isEmptyStr(orderItem.getCartId())) {
                QueryWrapper<Cart> wrapper = new QueryWrapper<>();
                wrapper.eq("uuid", orderItem.getCartId());
                Cart cart = cartMapper.selectOne(wrapper);
                cart.setIsDeleted(1);
                cartMapper.updateById(cart);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(String orderId) {
        // 删除相关订单信息
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", orderId);
        Order order = orderMapper.selectOne(queryWrapper);
        orderMapper.deleteById(order.getId());
        // 删除相关的订单明细信息
        QueryWrapper<OrderItem> listWrapper = new QueryWrapper<>();
        listWrapper.eq("order_id", order.getUuid());
        List<OrderItem> orderItems = orderItemMapper.selectList(listWrapper);
        for (OrderItem orderItem : orderItems) {
            orderItemMapper.deleteById(orderItem);
            // 还原购物车信息
            if (!Utils.isEmptyStr(orderItem.getCartId())) {
                QueryWrapper<Cart> cartWrapper = new QueryWrapper<>();
                cartWrapper.eq("uuid", orderItem.getCartId());
                cartWrapper.eq("is_deleted", "1");
                Cart cart = cartMapper.selectOne(cartWrapper);
                if (null != cart) {
                    cart.setIsDeleted(0);
                    cartMapper.updateById(cart);
                }
            }
        }
    }

    @Override
    public List<Order> getOrderList(String userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        for (Order order : orders) {
            QueryWrapper<OrderItem> listWrapper = new QueryWrapper<>();
            listWrapper.eq("order_id", order.getUuid());
            List<OrderItem> orderItems = orderItemMapper.selectList(listWrapper);
            fillOrderItems(orderItems);
            order.setOrderItemList(orderItems);
        }
        return orders;
    }

    private void fillOrderItems(List<OrderItem> list) {
        for (OrderItem orderItem : list) {
            String goodsId = orderItem.getGoodsId();
            QueryWrapper<Goods> goodWrapper = new QueryWrapper<>();
            goodWrapper.eq("uuid", goodsId);
            Goods goods = goodsMapper.selectOne(goodWrapper);
            orderItem.getParam().put("goods", goods);
        }
    }

    @Override
    public Order getOrderDetail(String orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", orderId);
        Order order = orderMapper.selectOne(queryWrapper);
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.eq("order_id", order.getUuid());
        List<OrderItem> orderItems = orderItemMapper.selectList(orderItemQueryWrapper);
        fillOrderItems(orderItems);
        order.setOrderItemList(orderItems);
        return order;
    }

}
